package com.xxc.hs.funActivity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.RecyclerView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.xxc.hs.R;
import com.xxc.hs.bean.DataInfo;
import com.xxc.hs.bean.DataType;
import com.xxc.hs.bean.DataTypeInt;
import com.xxc.hs.bean.UserInfo;
import com.xxc.hs.bean.WaterDataInfo;
import com.xxc.hs.funActivity.data.LeftAdapter;
import com.xxc.hs.funActivity.data.SensorViewModel;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class DataActivity extends AppCompatActivity {
    private static final String TAG = "DataActivity";
    private RecyclerView leftRecyclerView;
    private LeftAdapter leftAdapter;
    private LineChart lineChart;
    private SensorViewModel viewModel;
    private int currentDataType = DataTypeInt.TYPE_TEMPERATURE;
    private List<String> leftDataList = new ArrayList<>();
    // 定时刷新相关
    private Handler refreshHandler;
    private Runnable refreshRunnable;
    private static final long REFRESH_INTERVAL = 1000; // 1秒刷新间隔

    private List<?> lastData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data);

        try {
            leftRecyclerView = findViewById(R.id.leftRecyclerView);
            lineChart = findViewById(R.id.lineChart);

            initData();

            initChart();

            initViewModel();

            // 初始加载温度数据
            updateChartByType(DataTypeInt.TYPE_TEMPERATURE);

            //左边recyclerView的点击事件
            leftAdapter.setMleftListOnClickItemListener((position) -> {
                leftAdapter.setCurrentIndex(position);
                Log.d(TAG, "Clicked position: " + position);
                currentDataType = position;
                updateChartByType(currentDataType);
                // 延迟更新描述，确保数据加载完成
                updateChartDescription();
                startDataRefresh();
            });

            // 检查ViewModel是否有数据
            new Handler().postDelayed(this::checkViewModelData, 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 检查ViewModel数据的辅助方法
    private void checkViewModelData() {
        Log.d(TAG, "Temp data size: " + (viewModel.getTempData().getValue() != null ?
                viewModel.getTempData().getValue().size() : 0));
        Log.d(TAG, "Hum data size: " + (viewModel.getHumData().getValue() != null ?
                viewModel.getHumData().getValue().size() : 0));
        Log.d(TAG, "Smoke data size: " + (viewModel.getSmokeData().getValue() != null ?
                viewModel.getSmokeData().getValue().size() : 0));
        Log.d(TAG, "Fire data size: " + (viewModel.getFireData().getValue() != null ?
                viewModel.getFireData().getValue().size() : 0));
        Log.d(TAG, "WaterLevel data size: " + (viewModel.getWaterLevelData().getValue() != null ?
                viewModel.getWaterLevelData().getValue().size() : 0));
        Log.d(TAG, "PH data size: " + (viewModel.getPHData().getValue() != null ?
                viewModel.getPHData().getValue().size() : 0));
        Log.d(TAG, "Turbidity data size: " + (viewModel.getTurbidityData().getValue() != null ?
                viewModel.getTurbidityData().getValue().size() : 0));
        Log.d(TAG, "Dissolved data size: " + (viewModel.getDissolvedData().getValue() != null ?
                viewModel.getDissolvedData().getValue().size() : 0));
        Log.d(TAG, "YuLv data size: " + (viewModel.getYuLvData().getValue() != null ?
                viewModel.getYuLvData().getValue().size() : 0));
        Log.d(TAG, "WaterTemp data size: " + (viewModel.getWaterTempData().getValue() != null ?
                viewModel.getWaterTempData().getValue().size() : 0));
    }

    private void initData() {
        leftDataList.add("温度");
        leftDataList.add("湿度");
        leftDataList.add("烟雾");
        leftDataList.add("火焰");
        leftDataList.add("水位");
        leftDataList.add("PH");
        leftDataList.add("浊度");
        leftDataList.add("溶氧量");
        leftDataList.add("余氯");
        leftDataList.add("水温");

        leftAdapter = new LeftAdapter(leftDataList);
        leftRecyclerView.setAdapter(leftAdapter);
    }

    /**
     * 根据点击位置更新图表
     */
    private void updateChartByPosition(int position) {
        currentDataType = position;
        updateChartByType(currentDataType);
    }

    private void initViewModel(){
        // 初始化ViewModel
        viewModel = new SensorViewModel(getApplication(), UserInfo.getUserInfo().getType());
    }

    private void initChart() {
        lineChart.setTouchEnabled(true);
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(true);
        lineChart.setPinchZoom(true);
        lineChart.getDescription().setText("数据趋势图");
        lineChart.getDescription().setTextSize(14f);

        lineChart.setBackgroundColor(Color.WHITE);
        lineChart.setDrawGridBackground(false);

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setTextSize(10f);

        lineChart.getAxisLeft().setAxisMinimum(0f);
        lineChart.getAxisLeft().setAxisMaximum(100f);
        lineChart.getAxisLeft().setLabelCount(6, true);
        lineChart.getAxisLeft().setDrawGridLines(true);
        lineChart.getAxisLeft().setGridColor(Color.LTGRAY);
        lineChart.getAxisLeft().setTextSize(10f);

        lineChart.getAxisRight().setEnabled(false);

        lineChart.getLegend().setEnabled(true);
        lineChart.getLegend().setTextSize(12f);
        Legend legend = lineChart.getLegend();
        legend.setEnabled(true);
        legend.setTextSize(12f);

        // 适配不同版本的API
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);

        lineChart.invalidate();
    }

    // 新增方法：更新图表描述
    private void updateChartDescription() {
        String dataTypeName = getDataTypeName(currentDataType);
        Log.d(TAG, "Updating description to: " + dataTypeName);
        lineChart.getDescription().setText(dataTypeName);
        lineChart.invalidate();
    }

    // 新增方法：根据类型更新图表
    public void updateChartByType(int dataType) {
        this.currentDataType = dataType;
        // 清除之前的观察者（更安全的方式）
        removeObservers();

        // 根据数据类型观察不同的数据
        switch (dataType) {
            case DataTypeInt.TYPE_TEMPERATURE:
                observeData(viewModel.getTempData(), DataType.TEMPERATURE);
                setupYAxis(10f, 50f, 6);
                break;
            case DataTypeInt.TYPE_HUMIDITY:
                observeData(viewModel.getHumData(), DataType.HUMIDITY);
                setupYAxis(0f, 100f, 5);
                break;
            case DataTypeInt.TYPE_SMOKE:
                observeData(viewModel.getSmokeData(), DataType.SMOKE);
                setupYAxis(0f, 1f, 2);
                break;
            case DataTypeInt.TYPE_FIRE:
                observeData(viewModel.getFireData(), DataType.FIRE);
                setupYAxis(0f, 1f, 2);
                break;
            case DataTypeInt.TYPE_WATERLEVEL:
                observeData(viewModel.getWaterLevelData(), DataType.WATERLEVEL);
                setupYAxis(0f, 40f, 5);
                break;
            case DataTypeInt.TYPE_PH:
                observeData(viewModel.getPHData(), DataType.PH);
                setupYAxis(0f, 14f, 7); // PH值正常范围0-14，这里修正
                break;
            case DataTypeInt.TYPE_TURBIDITY:
                observeData(viewModel.getTurbidityData(), DataType.TURBIDITY);
                setupYAxis(0f, 100f, 5); // 浊度通常0-100NTU
                break;
            case DataTypeInt.TYPE_DISSOLVED:
                observeData(viewModel.getDissolvedData(), DataType.DISSOLVED);
                setupYAxis(0f, 15f, 4); // 溶氧量通常0-15mg/L
                break;
            case DataTypeInt.TYPE_YULV:
                observeData(viewModel.getYuLvData(), DataType.YULV);
                setupYAxis(0f, 5f, 3); // 余氯通常0-5mg/L
                break;
            case DataTypeInt.TYPE_WATERTEMP:
                observeData(viewModel.getWaterTempData(), DataType.WATERTEMP);
                setupYAxis(0f, 50f, 5); // 水温通常0-50℃
                break;
            default:
                observeData(viewModel.getTempData(), DataType.TEMPERATURE);
                setupYAxis(10f, 50f, 6);
        }

        // 刷新数据
        viewModel.refreshData(getDataTypeFromInt(dataType));

        // 添加日志确认数据刷新
        Log.d(TAG, "Refreshing data for type: " + dataType);
    }

    // 提取观察者设置为单独方法
    private <T> void observeData(LiveData<List<T>> liveData, DataType dataType) {
        liveData.removeObservers(this);

        liveData.observe(this, new Observer<List<T>>() {
            @Override
            public void onChanged(List<T> newData) {
                if (newData != null && !newData.isEmpty()) {
                    // 仅当数据变化时更新图表
                    if (lastData == null || lastData.size() != newData.size() || !newData.equals(lastData)) {
                        updateChart(newData);
                        lastData = newData;
                    }
                }
            }
        });
    }

    // 提取移除观察者的方法
    private void removeObservers() {
        viewModel.getTempData().removeObservers(this);
        viewModel.getHumData().removeObservers(this);
        viewModel.getSmokeData().removeObservers(this);
        viewModel.getFireData().removeObservers(this);
        viewModel.getWaterLevelData().removeObservers(this);
        viewModel.getPHData().removeObservers(this);
        viewModel.getTurbidityData().removeObservers(this);
        viewModel.getDissolvedData().removeObservers(this);
        viewModel.getYuLvData().removeObservers(this);
        viewModel.getWaterTempData().removeObservers(this);
    }

    // 提取Y轴设置为单独方法
    private void setupYAxis(float min, float max, int labelCount) {
        lineChart.getAxisLeft().setAxisMinimum(min);
        lineChart.getAxisLeft().setAxisMaximum(max);
        lineChart.getAxisLeft().setLabelCount(labelCount, true);

        lineChart.invalidate();
        lineChart.fitScreen();
    }

    /**
     * 根据整数类型获取DataType枚举
     */
    private DataType getDataTypeFromInt(int dataType) {
        switch (dataType) {
            case DataTypeInt.TYPE_TEMPERATURE:
                return DataType.TEMPERATURE;
            case DataTypeInt.TYPE_HUMIDITY:
                return DataType.HUMIDITY;
            case DataTypeInt.TYPE_SMOKE:
                return DataType.SMOKE;
            case DataTypeInt.TYPE_FIRE:
                return DataType.FIRE;
            case DataTypeInt.TYPE_WATERLEVEL:
                return DataType.WATERLEVEL;
            case DataTypeInt.TYPE_PH:
                return DataType.PH;
            case DataTypeInt.TYPE_TURBIDITY:
                return DataType.TURBIDITY;
            case DataTypeInt.TYPE_DISSOLVED:
                return DataType.DISSOLVED;
            case DataTypeInt.TYPE_YULV:
                return DataType.YULV;
            case DataTypeInt.TYPE_WATERTEMP:
                return DataType.WATERTEMP;
            default:
                return DataType.TEMPERATURE;
        }
    }

    private <T> void updateChart(List<T> dataList) {
        Log.d(TAG, "Updating chart with " + dataList.size() + " data points for type: " + currentDataType);

        if (dataList == null || dataList.isEmpty()) {
            Log.w(TAG, "Data list is empty or null");
            lineChart.clear();
            lineChart.invalidate();
            return;
        }

        List<String> xLabels = new ArrayList<>();
        List<Entry> entries = new ArrayList<>();

        try {
            for (int i = 0; i < dataList.size(); i++) {
                T item = dataList.get(i);
                String timeLabel = "时间" + i;
                String valueStr = "0";

                if (item instanceof DataInfo) {
                    DataInfo data = (DataInfo) item;

                    Log.e(TAG,data.getTime());
                    timeLabel = (data.getTime() != null ? data.getTime() : "时间" + i).substring(11, 19);

                    switch (currentDataType) {
                        case DataTypeInt.TYPE_TEMPERATURE:
                            valueStr = data.getTemp() != null ? data.getTemp() : "0";
                            break;
                        case DataTypeInt.TYPE_HUMIDITY:
                            valueStr = data.getHum() != null ? data.getHum() : "0";
                            break;
                        case DataTypeInt.TYPE_SMOKE:
                            valueStr = (data.getSmoke() != null) ? String.valueOf(data.getSmoke()) : "0";
                            break;
                        case DataTypeInt.TYPE_FIRE:
                            valueStr = data.getFire() != null ? String.valueOf(data.getFire()) : "0";
                            break;
                    }
                } else if (item instanceof WaterDataInfo) {
                    WaterDataInfo waterData = (WaterDataInfo) item;
                    timeLabel = (waterData.getTime() != null ? waterData.getTime() : "时间" + i).substring(11, 19);

                    switch (currentDataType) {
                        case DataTypeInt.TYPE_WATERLEVEL:
                            valueStr = waterData.getWaterLevel() != null ? waterData.getWaterLevel() : "0";
                            break;
                        case DataTypeInt.TYPE_PH:
                            valueStr = waterData.getPh() != null ? waterData.getPh() : "0";
                            break;
                        case DataTypeInt.TYPE_TURBIDITY:
                            valueStr = waterData.getTurbidity() != null ? waterData.getTurbidity() : "0";
                            break;
                        case DataTypeInt.TYPE_DISSOLVED:
                            valueStr = waterData.getDissolved() != null ? waterData.getDissolved() : "0";
                            break;
                        case DataTypeInt.TYPE_YULV:
                            valueStr = waterData.getYuLv() != null ? waterData.getYuLv() : "0";
                            break;
                        case DataTypeInt.TYPE_WATERTEMP:
                            valueStr = waterData.getWaterTemp() != null ? waterData.getWaterTemp() : "0";
                            break;
                    }
                }

                xLabels.add(timeLabel);

                try {
                    float value = Float.parseFloat(valueStr);
                    entries.add(new Entry(i, value));
                } catch (NumberFormatException e) {
                    Log.e(TAG, "Failed to parse value: " + valueStr, e);
                    entries.add(new Entry(i, 0));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (entries.isEmpty()) {
            Log.w(TAG, "No valid entries to display");
            lineChart.clear();
            lineChart.invalidate();
            return;
        }

        LineDataSet dataSet;
        LineData lineData = lineChart.getData();

        if (lineData != null && lineData.getDataSetCount() > 0) {
            // 更新现有数据集
            dataSet = (LineDataSet) lineData.getDataSetByIndex(0);
            dataSet.clear();

            // 关键：更新现有数据集的标签
            dataSet.setLabel(getDataTypeName(currentDataType));

            // 逐个添加新数据点
            for (Entry entry : entries) {
                dataSet.addEntry(entry);
            }
        } else {
            // 创建新数据集
            dataSet = new LineDataSet(entries, getDataTypeName(currentDataType));
            lineData = new LineData(dataSet);
            lineChart.setData(lineData);
        }

        // 设置数据集样式
        if (dataSet != null) {
            setDataSetColor(dataSet, currentDataType);

            dataSet.setLineWidth(2f);
            dataSet.setCircleRadius(4f);
            dataSet.setCircleHoleRadius(2f);
            dataSet.setValueTextSize(10f);
            dataSet.setDrawValues(true);
            dataSet.setValueTextColor(Color.BLACK);
        } else {
            Log.e(TAG, "DataSet is null, cannot set style");
            return;
        }


        XAxis xAxis = lineChart.getXAxis();
        xAxis.setValueFormatter(new IndexAxisValueFormatter(xLabels));
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(Math.min(dataList.size(), 10));

        lineChart.notifyDataSetChanged();
        lineChart.postInvalidateOnAnimation();
    }


    /**
     * 解析字符串时间戳为时分秒（不包含毫秒）
     */
    private String parseStringTimestampWithoutMs(String timestampStr) {
        if (timestampStr == null || timestampStr.isEmpty()) {
            return "时间戳为空";
        }

        try {
            long timestamp = Long.parseLong(timestampStr);
            Date date = new Date(timestamp);

            // 格式：HH:mm:ss
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
            return formatter.format(date);

        } catch (Exception e) {
            e.printStackTrace();
            return "解析失败";
        }
    }

    // 单独设置数据集颜色
    private void setDataSetColor(LineDataSet dataSet, int dataType) {
        switch (dataType) {
            case DataTypeInt.TYPE_TEMPERATURE:
                dataSet.setColor(Color.RED);
                dataSet.setCircleColor(Color.RED);
                break;
            case DataTypeInt.TYPE_HUMIDITY:
                dataSet.setColor(Color.BLUE);
                dataSet.setCircleColor(Color.BLUE);
                break;
            case DataTypeInt.TYPE_SMOKE:
                dataSet.setColor(Color.GRAY);
                dataSet.setCircleColor(Color.GRAY);
                break;
            case DataTypeInt.TYPE_FIRE:
                dataSet.setColor(Color.RED); // 火焰数据使用红色更合理
                dataSet.setCircleColor(Color.RED);
                break;
            case DataTypeInt.TYPE_WATERLEVEL:
                dataSet.setColor(Color.BLUE); // 水位数据使用蓝色更合理
                dataSet.setCircleColor(Color.BLUE);
                break;
            case DataTypeInt.TYPE_PH:
                dataSet.setColor(Color.GREEN); // PH数据使用绿色
                dataSet.setCircleColor(Color.GREEN);
                break;
            case DataTypeInt.TYPE_TURBIDITY:
                dataSet.setColor(Color.YELLOW); // 浊度数据使用黄色
                dataSet.setCircleColor(Color.YELLOW);
                break;
            case DataTypeInt.TYPE_DISSOLVED:
                dataSet.setColor(Color.CYAN); // 溶氧量使用青色
                dataSet.setCircleColor(Color.CYAN);
                break;
            case DataTypeInt.TYPE_YULV:
                dataSet.setColor(Color.MAGENTA); // 余氯使用洋红色
                dataSet.setCircleColor(Color.MAGENTA);
                break;
            case DataTypeInt.TYPE_WATERTEMP:
                dataSet.setColor(Color.RED); // 水温使用红色
                dataSet.setCircleColor(Color.RED);
                break;
            default:
                dataSet.setColor(Color.BLACK);
                dataSet.setCircleColor(Color.BLACK);
        }
    }

    /**
     * 根据数据类型获取显示名称
     */
    private String getDataTypeName(int dataType) {
        switch (dataType) {
            case DataTypeInt.TYPE_TEMPERATURE:
                return "温度数据(℃)";
            case DataTypeInt.TYPE_HUMIDITY:
                return "湿度数据(%)";
            case DataTypeInt.TYPE_SMOKE:
                return "烟雾数据";
            case DataTypeInt.TYPE_FIRE:
                return "火焰数据";
            case DataTypeInt.TYPE_WATERLEVEL:
                return "水位数据";
            case DataTypeInt.TYPE_PH:
                return "PH数据";
            case DataTypeInt.TYPE_TURBIDITY:
                return "浊度数据";
            case DataTypeInt.TYPE_DISSOLVED:
                return "溶氧量数据";
            case DataTypeInt.TYPE_YULV:
                return "余氯数据";
            case DataTypeInt.TYPE_WATERTEMP:
                return "水温数据";
            default:
                return "数据";
        }
    }


    // 启动数据刷新定时任务
    private void startDataRefresh() {
        if (refreshHandler == null) {
            refreshHandler = new Handler(Looper.getMainLooper());
        }

        if (refreshRunnable == null) {
            refreshRunnable = new Runnable() {
                @Override
                public void run() {
                    // 刷新当前类型的数据
                    viewModel.refreshData(getDataTypeFromInt(currentDataType));
                    // 重新设置定时任务
                    refreshHandler.postDelayed(this, REFRESH_INTERVAL);
                }
            };
        }

        // 移除可能存在的旧任务
        refreshHandler.removeCallbacks(refreshRunnable);
        // 延迟1秒后开始第一次刷新，之后每秒刷新
        refreshHandler.postDelayed(refreshRunnable, REFRESH_INTERVAL);
        Log.d(TAG, "Started data refresh with interval: " + REFRESH_INTERVAL + "ms");
    }

    // 停止数据刷新定时任务
    private void stopDataRefresh() {
        if (refreshHandler != null && refreshRunnable != null) {
            refreshHandler.removeCallbacks(refreshRunnable);
            Log.d(TAG, "Stopped data refresh");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            removeObservers();
            stopDataRefresh();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}